package com.demo.springsecuritystudy.configuration;

import com.alibaba.fastjson2.JSON;
import com.demo.springsecuritystudy.enhancer.JWTTokenEnhancer;
import com.demo.springsecuritystudy.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.token.TokenEnhancer;
import org.springframework.security.oauth2.provider.token.TokenEnhancerChain;
import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;
import org.springframework.security.oauth2.provider.token.store.JwtTokenStore;
import org.springframework.util.Assert;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * 授权服务器配置
 */
@Slf4j
@Configuration
@EnableAuthorizationServer
public class AuthorizationServerConfiguration extends AuthorizationServerConfigurerAdapter {

    @Value("${application.customize.username:admin}")
    private String customizeUsername;

    @Value("${application.customize.password:123}")
    private String customizePassword;

    @Resource
    private PasswordEncoder passwordEncoder;
    @Resource
    private AuthenticationManager authenticationManager;
    @Resource
    private UserService userService;
    @Resource
    @Qualifier("jwtTokenStore")
    private JwtTokenStore jwtTokenStore;
    @Resource
    private JwtAccessTokenConverter jwtAccessTokenConverter;
    @Resource
    private JWTTokenEnhancer jwtTokenEnhancer;
    @Resource
    private TokenEnhancerChain tokenEnhancerChain;
    private List<TokenEnhancer> tokenEnhancerList;
    @PostConstruct
    public void init() {
        // 配置JWT增强内容
        this.tokenEnhancerList = new ArrayList<TokenEnhancer>() {{
            add(jwtTokenEnhancer);
            add(jwtAccessTokenConverter);
        }};
        log.info("tokenEnhancer list value is {}", JSON.toJSONString(this.tokenEnhancerList));
        Assert.isTrue(tokenEnhancerList.size() > 0, "tokenEnhancerList add element Exception list size is zero");
        tokenEnhancerChain.setTokenEnhancers(tokenEnhancerList);
    }

    /**
     * 使用密码模式配置
     * @param endpointsConfigurer
     * @throws Exception
     */
    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpointsConfigurer) throws Exception {
        endpointsConfigurer.authenticationManager(authenticationManager)
                            .userDetailsService(userService)
                            .tokenStore(jwtTokenStore)
                            .accessTokenConverter(jwtAccessTokenConverter)
                            .tokenEnhancer(tokenEnhancerChain);
    }
    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        clients.inMemory()
                // 配置Client id
                .withClient(customizeUsername)
                // 配置Client Secret
                .secret(passwordEncoder.encode(customizePassword))
                // 配置token的有效期
                .accessTokenValiditySeconds(3600)
                // 配置刷新token有效期
                .refreshTokenValiditySeconds(864000)
                // 配置redirect uri,用于授权成功后跳转
                .redirectUris("http://localhost:8081/login")
                // 自动授权
                .autoApprove(true)
                // 配置申请的权限范围
                .scopes("all")
                // 配置grant_type,表示授权类型即授权模式
                .authorizedGrantTypes("password", "refresh_token", "authorization_code");
    }

    @Override
    public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
        // 获取密钥需要身份认证，使用单点登录时需要配置
        security.tokenKeyAccess("isAuthenticated()");
    }
}
